<?php
namespace app\cut_pic\controller;
use think\Controller;

class Crop extends Controller{

    public function index(){
        return $this->fetch();
    }

    public function img_upload(){
        //上传图片后，把图片复制到upload文件夹下面
        if($_POST){
            $photo = $_FILES['img']['name'];
            $tmp_addr = $_FILES['img']['tmp_name'];

            $path = 'cut_upload/';
            $type=array("jpg","gif","jpeg","png");
            $tool = substr(strrchr($photo,'.'),1);
            if(!in_array(strtolower($tool),$type)){
                $text=implode('.',$type);
                echo "您只能上传以下类型文件: ",$text,"<br>";
            }else{
                $filename = explode(".",$photo);                       //把上传的文件名以"."好为准做一个数组。
                $time = date("m-d-H-i-s");                            //取当前上传的时间
                $filename[0] = $time;                                //取文件名
                $name = implode(".",$filename);                     //上传后的文件名
                $uploadfile = $path.$name;
                $_SESSION['upfile'] = $uploadfile;//上传后的文件名地址
                move_uploaded_file($tmp_addr,$uploadfile);
            }
//    echo  $uploadfile;
        }
    }


    function sliceBanner(){
        $x = request()->param('x');
        $y = request()->param('y');
        $w = request()->param('w');
        $h = request()->param('h');

        //剪切后小图片的名字
        $pic = request()->param('pic');
        $str = explode(".",$pic);
        $type = $str[1];
        $filename = "case.". $type;

        $uploadBanner =  $pic;
        $sliceBanner = 'upload/images/'. $filename;//剪切后的图片存放的位置

        //创建图片
        $src_pic = getImageHander($uploadBanner);
        $dst_pic = imagecreatetruecolor($w, $h);
        imagecopyresampled($dst_pic, $src_pic, 0, 0, $x, $y, $w, $h, $w, $h);
        imagejpeg($dst_pic, $sliceBanner);
        imagedestroy($src_pic);
        imagedestroy($dst_pic);

        //返回新图片的位置
        echo  $sliceBanner;
    }

    //初始化图片
    function getImageHander ($url) {
        $size=@getimagesize($url);
        switch($size['mime']){
            case 'image/jpeg': $im = imagecreatefromjpeg($url);break;
            case 'image/gif' : $im = imagecreatefromgif($url);break;
            case 'image/png' : $im = imagecreatefrompng($url);break;
            default: $im=false;break;
        }

        return $im;
    }
}